import cv2
import numpy as np

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread('cola.jpg')
    if image_np is None:  # 增加图片读取失败判断
        print("无法读取图片，请检查路径是否正确")
        exit()

    # 2. HSV空间转换
    hsv_image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)

    # 3. 调整蓝色HSV范围（仅覆盖百事瓶身和瓶盖的蓝色）
    blue_low = np.array([105, 100, 100])
    blue_high = np.array([120, 255, 255])
    mask = cv2.inRange(hsv_image_np, blue_low, blue_high)

    # 4. 形态学开运算+闭运算（先降噪再补全边缘）
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    open_mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
    close_mask = cv2.morphologyEx(open_mask, cv2.MORPH_CLOSE, kernel, iterations=4)

    # 5. 颜色替换
    for i in range(close_mask.shape[0]):
        for j in range(close_mask.shape[1]):
            if close_mask[i, j] == 255:
                # 将蓝色区域替换为红色（BGR格式：(0, 0, 255)）
                image_np[i, j] = (0, 0, 255)

    # 6. 图片输出
    cv2.namedWindow('Result1', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('Result1', 800, 600)
    cv2.namedWindow('Result2', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('Result2', 800, 600)
    cv2.imshow('Result1', close_mask)
    cv2.imshow('Result2', image_np)
    cv2.imwrite('cola.png', image_np)
    cv2.waitKey(0)